#ifndef CALCULATE_BENDED_PIPE_OF_SINGLE_ELEMENT_H
#define CALCULATE_BENDED_PIPE_OF_SINGLE_ELEMENT_H

#include "cnpipe_global.h"
#include "cnpipe_piperangedefiner.h"

#include "geometry/averagevector.h"
#include "geometry/math3d.h"

#include "CNPIPEUtils/bendedelement.h"

#define _USE_MATH_DEFINES
#include <math.h>

/** 计算单一节点的半径和参考点 center:弯头的圆心，reference:弯头的参考点 */
BendedElement *CalculateBendedPipeOfSingleElement(QMap<QString, QList<Vector3D *> *> *element,
                                        CNPIPE_global *global) {
    CNPIPE_pipeRangeDefiner *rd = (CNPIPE_pipeRangeDefiner *)global->getPipeRangeDefiner();

    int nodeCount = element->count();
    if (nodeCount != 2) return NULL;

    QList<QString> nodeNames = element->keys();
    QString node1Name = nodeNames.at(0), node2Name = nodeNames.at(1);

    QList<Vector3D*> *node1Vectors = element->value(node1Name),
            *node2Vectors = element->value(node2Name);

    Vector3D *referenceVectorOfNode1 = AverageVector(node1Vectors),
            *referenceVectorOfNode2 = AverageVector(node2Vectors);
    double bendedAngle = M_PI - Math3D::angleOfTwoVectorsInRad(referenceVectorOfNode1, referenceVectorOfNode2);

    CNPIPE_singleNode *node1 = rd->getSingleNode(node1Name);
    CNPIPE_singleNode *node2 = rd->getSingleNode(node2Name);

    Vertex3D *node1Vertex = rd->AdjustSingleNodeWithinRange(node1);
    Vertex3D *node2Vertex = rd->AdjustSingleNodeWithinRange(node2);

    Vertex3D *middleVertex = Math3D::middleVertex(node1Vertex, node2Vertex);
    Vector3D *node1Node2Vector = Math3D::direction(node1Vertex, node2Vertex);

    Vector3D *crossVector1 = Math3D::crossVectors(referenceVectorOfNode1, referenceVectorOfNode2);
    Vector3D *vectorToCenter = Math3D::crossVectors(node1Node2Vector, crossVector1);
    Vertex3D *centerOfTheBendedElement = middleVertex->addVectors(
                vectorToCenter->normalize()->multiply(node1Node2Vector->length() / 2 / tan(bendedAngle / 2)));

    double radius = Math3D::direction(centerOfTheBendedElement, node1Vertex)->length();

    qDebug() << "RADIUS 1:" << Math3D::direction(centerOfTheBendedElement, node1Vertex)->length();
    qDebug() << "RADIUS 2:" << Math3D::direction(centerOfTheBendedElement, node2Vertex)->length();
    qDebug() << "DISTANCE BETWEEN CENTER AND NODE 1:" << node1Node2Vector->length() / 2 / tan(bendedAngle / 2);
    qDebug() << "DISTANCE BETWEEN CENTER AND NODE 2:" << radius * cos(bendedAngle / 2);

    Vertex3D *referenceVertex = centerOfTheBendedElement->addVectors(
                vectorToCenter->normalize()->multiply(-radius / cos(bendedAngle / 2)));

    BendedElement *b = new BendedElement(node1Vertex, node2Vertex,
                                         centerOfTheBendedElement, referenceVertex, radius);

    return b;
}

#endif //CALCULATE_BENDED_PIPE_OF_SINGLE_ELEMENT_H
